package com.chee.plant.server;

import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

import com.chee.plant.logic.CmdExcutor;

public class SessionServer {
	private BlockingQueue<Message> _sendMsgQueue;
	private BlockingQueue<Message> _recvMsgQueue;
	private ExecutorService _workerService;
	private OverdueThread _overdueThread;
	private SendThread _sendThread;
	private RecvThread _recvThread;
	public SessionServer(){
		this._sendMsgQueue = new LinkedBlockingQueue<Message>();
		this._recvMsgQueue = new LinkedBlockingQueue<Message>();
		this._workerService = Executors.newCachedThreadPool();
		this._overdueThread = new OverdueThread();
		this._sendThread = new SendThread();
		this._recvThread = new RecvThread();
		this._workerService.execute(this._overdueThread);
	}
	public boolean addSendMessage(Message msg){
		this._sendMsgQueue.offer(msg);
		CommonData.refreshUser(msg.getUserId());
		this._workerService.execute(this._sendThread);
		return true;
	}
	public boolean addRecvMessage(Message msg){
		this._recvMsgQueue.offer(msg);
		CommonData.refreshUser(msg.getUserId());
		this._workerService.execute(this._recvThread);
		return true;
	}
	class OverdueThread implements Runnable {
		public void run(){
			while (true) {
				try {
					CommonData.removeOverdueUser();
					CommonData.removeOverdueRawSession();
					Thread.sleep(600000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	class SendThread implements Runnable {
		public void run(){
			if(_sendMsgQueue.size() == 0) return;
			Message msg = _sendMsgQueue.poll();
			while(msg != null){
				int userId = msg.getUserId();
				if(userId > 0){
					// do send
					SessionEntity session = CommonData.getSession(msg.getUserId());
					if(session != null) session.sendMessage(msg);
					
				}else if(userId == 0){
					Collection<SessionEntity> coll = CommonData.getOnlineUsers().values();
					Iterator<SessionEntity> iter = coll.iterator();
					while (iter.hasNext()) {
						SessionEntity entry = iter.next();
						entry.sendMessage(msg);
					}
				}else{}
				msg = _sendMsgQueue.poll();
			}
		}
	}
	class RecvThread implements Runnable {
		public void run(){
			if(_recvMsgQueue.size() == 0) return;
			Message msg = _recvMsgQueue.poll();
			while(msg != null){
				// do send
				Vector<Message> result = CmdExcutor.executeCmd(msg);
				Enumeration<Message> enu = result.elements();
				while(enu.hasMoreElements()) addSendMessage(enu.nextElement());
				msg = _recvMsgQueue.poll();
			}
		}
	}
}
